package net.yeah.mickey_zhouyou.database.sequence;

import net.yeah.mickey_zhouyou.database.domain.BaseEntity;
import net.yeah.mickey_zhouyou.database.exception.SequenceExceed;

/**
 * 序列类型。 此类型会为每个实体类型自动的创建，外部用户不必关心。
 * 
 * @author Mickey
 * 
 */
public final class Sequence {

	/**
	 * 希望在我有生之年，这个值还够大。
	 */
	private long nextValue = 0;
	private String entityName = null;

	private Sequence(String className) {
		this.entityName = className;
	}

	public String getEntityName() {
		return this.entityName;
	}

	public Class<?> getEntityType() {
		try {
			return Class.forName(entityName);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static <E extends BaseEntity> Sequence createSequence(
			Class<E> clazz) {
		return new Sequence(clazz.getName());
	}

	public synchronized long nextValue() {
		if (nextValue < Long.MAX_VALUE) {
			return nextValue += 1;
		}
		throw new SequenceExceed();
	}

}
